package test;

import way.learning.zz.event.*;
import way.learning.zz.listener.DirectoryListener;
import way.learning.zz.listener.InitialContentListener;
import way.learning.zz.listener.IoErrorListener;
import way.learning.zz.source.FileElement;
import way.learning.zz.source.FtpFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MyListener implements DirectoryListener, IoErrorListener, InitialContentListener {


    private String filename;

    /**
     * 事件源产生事件，这里的事件源就是监视的目录了，但是
     */
    @Override
    public void fileAdded(FileAddedEvent event) {
        System.out.println("Added: " + event.getFileElement());
        FtpFile ftpFile = (FtpFile) event.getFileElement();

        filename = ftpFile.getName();
        System.out.println("size: "+ftpFile.getSize());
    }

    public String getNewFileName(){

        return filename;
    }

    public List<FileElement> newFileAdd(FileAddedEvent event){
        ArrayList<FileElement> fileElementList = new ArrayList<FileElement>();
        FileElement fileElement = event.getFileElement();

        //如果监视目录下出现了新文件，则将文件添加到List中
        if(!fileElement.isDirectory()){
            fileElementList.add(fileElement);
        }

        return fileElementList;
    }

    @Override
    public void fileRemoved(FileRemovedEvent event) {
        System.out.println("Removed: " + event.getFileElement());
    }

    @Override
    public void fileModified(FileModifiedEvent event) {
        System.out.println("Modified: " + event.getFileElement());
    }

    @Override
    public void ioErrorCeased(IoErrorCeasedEvent event) {
        System.out.println("I/O error ceased.");
    }

    @Override
    public void ioErrorRaised(IoErrorRaisedEvent event) {
        System.out.println("I/O error raised!");
        event.getIoException().printStackTrace();
    }

    @Override
    public void initialContent(InitialContentEvent event) {
        System.out.println("initial Content: ");
        Set<FileElement> files = event.getFiles();
        for (FileElement fileElement : files){
            System.out.println(fileElement.getName());
        }
    }
}